<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <select class="province">
        <option value="">请选择省份</option>
        <!-- <option value="A001">北京</option>
        <option value="A002">上海</option>
        <option value="A003">湖北</option>
        <option value="A004">湖南</option> -->
    </select>
    <select class="city" name="" id="">
        <option value="">请选择市/区</option>
        <!-- <option value="A001">朝阳</option>
        <option value="A002">海淀</option>
        <option value="A003">沙河</option>
        <option value="A004">上地</option> -->
    </select>
</body>
<script>
    // 省市二级联动
    // 1. 先请求数据
    // 2. 根据请求的数据动态生成 option 放到select框中
    //    下拉框取值:value   设置select内的结构innerHTML
    // 3. 当省份下拉框切换时 => 对应省份名称或编号 => 找到该省份数据 => 获取对应省份找到城市的集合 =>  动态生成城市的下拉框 (2级)
    // 4. 当城市下拉框切换时 => 对应城市名称或编号 => 找到该城市数据 => 获取对应城市找到市区的集合 =>  动态生成市区的下拉框 (3级)

    var proSel = document.getElementsByClassName("province")[0];
    var citySel = document.getElementsByClassName("city")[0];


    var xhr = new XMLHttpRequest();  // 0

    xhr.open("get", "../data/pro.json", true);  // 1

    xhr.send();  // 1

    xhr.onreadystatechange = function () {
        //  2  3  4
        console.log(xhr.readyState);
        if (xhr.readyState == 4 && xhr.status == 200) {
            var result = xhr.responseText; // json字符串
            var data = JSON.parse(result);
            console.log(data);

            var { list: proList } = data;
            console.log(proList);

            var html = "<option value=''>请选择省份</option>";
            // proList.forEach((item) => {
            //     var { city_id, city_name } = item;
            //     html += `<option value="${city_id}">${city_name}</option>`
            // })
            proList.forEach(({ city_id, city_name }) => {
                html += `<option value="${city_id}">${city_name}</option>`
            })
            proSel.innerHTML = html;



            proSel.onchange = function () {
                var cityId = this.value; //切换后的cityId
                console.log(cityId);
                if (cityId) { // 有值 
                    var thisPro = proList.find(({ city_id, city_name }) => {
                        return city_id == cityId;
                    })
                    console.log(thisPro);

                    var { list: cityList } = thisPro;

                    var html = "<option value=''>请选择市/区</option>";
                    cityList.forEach(({ city_id, city_name }) => {
                        html += `<option value="${city_id}">${city_name}</option>`
                    })
                    citySel.innerHTML = html;
                } else { // 切回到  请选择 => 选项
                    citySel.innerHTML = "<option value=''>请选择市/区</option>";
                }
            }


        }
    }






</script>

</html>